﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// Control that displays an emailaddress by using javascript, to (hopefully) prevent spambots to grab this emailaddress.
    /// </summary>
    /// <example>
    ///     <goodstuff:MaskedEmailDisplayText ID="myID" Email="dummy@mydomain.com" runat="server" />
    /// </example>
    public class MaskedEmailDisplayText : Control
    {
        /// <summary>
        /// Full E-mailaddress to display with use of javascript.
        /// </summary>
        public string Email { get; set; }

        /// <summary>
        /// Renders a javascript for showing the emailaddress
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            if (!string.IsNullOrEmpty(this.Email) && this.Email.Contains("@"))
            {
                int atIndex = this.Email.IndexOf('@');

                string address = this.Email.Substring(0, atIndex);
                string domein = this.Email.Remove(0, atIndex);

                //there we go
                writer.Write(@"<script language=""Javascript"">");
                writer.Write(string.Format(@"domain = '{0}';", domein));
                writer.Write(string.Format(@"document.write('{0}');", address));
                writer.Write(@"document.write(domain);");
                writer.Write(@"</script>");            
            }
        }
    }
}
